﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;


namespace nadModel
{
    public class LogManager
    {
        private static LogManager instance;
        private Logger loggerForAll;
        private Dictionary<string, Logger> loggerMap = new Dictionary<string, Logger>();

        private LogManager(Logger logger)
        {
            this.loggerForAll = logger;
        }

        public void AddLogger(string type, Logger logger)
        {
            this.loggerMap.Add(type, logger);
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public static LogManager CreateLogManager(Logger logger)
        {
            instance = new LogManager(logger);
            return instance;
        }

        private string FormatLogMessage(string msg, LogLevel lvl, string type)
        {
            DateTime now = DateTime.Now;
            return ("[PAD]" + string.Format("[{0:u}] ", now) + lvl.ToString() + ":" + type + ":" + msg);
        }

        public static LogManager GetInstance(string lvl = "DEBUG")
        {
            if (instance == null)
            {
                TextFileLogger logger = new TextFileLogger(AppDomain.CurrentDomain.BaseDirectory, LogLevelHelper.ParseLevel(lvl));
                instance = LogManager.CreateLogManager(logger);
            }
            return instance;
        }

        public void Log(string msg, LogLevel logLevel, object caller)
        {
            if ((this.loggerForAll != null) && (caller != null))
            {
                string type = caller.GetType().ToString();
                string str3 = this.FormatLogMessage(msg, logLevel, type);
                this.loggerForAll.Log(str3, logLevel);
                using (Dictionary<string, Logger>.KeyCollection.Enumerator enumerator = this.loggerMap.Keys.GetEnumerator())
                {
                    while (enumerator.MoveNext())
                    {
                        string current = enumerator.Current;
                        if (type.StartsWith(current))
                        {
                            this.loggerMap[current].Log(str3, logLevel);
                        }
                    }

                }
            }
        }
    }
}
